<template>
  <view class="listWrapper" :style="{
                padding:'0px ' + properties.setStyle.pageMargin+'px'
              }">
    <uv-notify ref="notify" message="success" type="success"></uv-notify>

    <view v-for="(item,index) in localDatas">

      <view class="order-card" :style="{
                'border-radius':properties.setStyle.borderRadius+'px',
                'background-color': properties.setStyle.backgroundColor,
                'min-height':'35px',
                padding: properties.setStyle.padding+'px',
                width:'100%'
              }">
        <view class="head">
          <slot name="head">
            <view class="left" @click="goDetail(item)">
              <view class="avatar">
                <uv-avatar size="42" :src="item.memberAvatar || (item.memberUser && item.memberUser.avatar)"></uv-avatar>
              </view>
              <view class="name">
                <view class="uName">
                  <uv-tags size="mini" v-if="item.marketTag" v-for="tag in item.marketTag" :text="tag" type="error"></uv-tags>
                  <view>{{ item.orderName }}</view>
                </view>
                <view class="time">
                  {{ item.timeBelongFormat }}
                </view>
              </view>
            </view>

            <view @click="goDetail(item)" class="center">
              <slot name="orderAmountValue">
                <view class="money" :style="{
                  color: commonStyle.theme.color
                }">
                  <text>酬金：</text>
                  <text class="amountValue">{{ item.takeAmount }}</text>
                  <text>元</text>
                </view>
              </slot>
            </view>

            <slot name="orderState">
              <view style="display: flex;align-items: center;flex-direction: column">
                <view @click="goDetail(item)" class="right">
                  <Dict :properties="{dictType:'order_state',dictValue:item.state,size:'mini'}"/>
                </view>
              </view>
            </slot>
          </slot>
        </view>

        <view @click="copyOrder(item.orderNo)" class="orderNo-wrapper">
          <view style="display:flex;">
            <view class="orderno">{{ item.orderNo }}</view>
            <view>
              <uv-icon name="empty-news"></uv-icon>
            </view>
          </view>
          <view>
            <slot name="cancel-reason">
              <uv-text type="info" :text="getCancelText(item)"/>
            </slot>
          </view>
        </view>


        <slot name="address">
          <view @click="goDetail(item)" class="address">
            <view class="actionAddress" style="color: #606266">
              <view style="display: flex">
                <uv-icon name="/static/images/start.png" size="25"/>
                <view>{{item.actionAddress}}</view>
              </view>
              <uv-gap height="10"/>
              <view style="display: flex">
                <uv-icon name="/static/images/end.png" size="25"/>
                <view>{{item.destination}}</view>
              </view>
            </view>
          </view>
        </slot>

        <view class="body_time" v-if="item.deliveryTime">
          <uv-icon :color="themConfig.theme.subColor" size="13" name="clock"></uv-icon>
          <view :style="{color:themConfig.theme.subColor}">期望送达时间：{{ item.deliveryTime }}</view>
        </view>

        <slot name="body">
          <view class="body">
            <view class="content" @click="goDetail(item)" style="">
              <view>备注：
                <text v-if="item.skuName">【{{ item.skuName }}x{{ item.num }}】</text>
              </view>
              <view style="text-indent: 1em;margin-top: 10rpx">
                <rich-text :nodes="item.content"></rich-text>
              </view>
            </view>

            <view v-if="item.platformAuditResult!=null && item.platformAuditResult!=''" class="content" @click="goDetail(item)"
                  style="display: flex;margin-top: 20rpx">
              审核：
              <rich-text :nodes="item.platformAuditResult"></rich-text>
            </view>


            <view style="margin: 5px 0px" v-if="item.photos && item.photos.length">
              <view>
                <uv-album :multipleSize="50" :singleSize="50" :urls="item.photos"></uv-album>
              </view>
            </view>

            <view style="margin: 5px 0px" v-if="item.signForPictures">
              <view>
                <uv-album :multipleSize="50" :singleSize="50" :urls="[item.signForPictures]"></uv-album>
              </view>
            </view>


            <view @click="goDetail(item)"
                  v-if="item.sensitiveContent!=undefined && item.sensitiveContent!==null && item.sensitiveContent !==''">
              <view class="sentive">
                {{ item.sensitiveContent }}
              </view>
            </view>
          </view>
        </slot>


        <uv-divider text=" " :dashed="true"></uv-divider>

        <slot name="operate">
          <view class="operate">
            <view class="accept" v-if="item.identity==='1' && item.state===1">
              <view class="butt">
                <uv-button :customStyle="{
                width: '100%'
              }" @click="acctOrder(item)" type="success" size="normal"
                           text="接单"></uv-button>
              </view>
            </view>

            <view class="accept" v-if="item.identity==='1' && item.state===2">
              <view class="butt">
                <view class="butt">
                  <uv-button @click="finish(item,false)" type="success" :color="commonStyle.theme.color" size="normal"
                             plain
                             text="送达"></uv-button>
                </view>
              </view>
            </view>

            <view class="accept"
                  v-if="item.identity==='2'
                && (item.state===11 ||item.state===100 || item.state===101 || item.state===0 || item.state===1 || item.state === -1 )
                && uid === item.memberId ">
              <view class="butt">
                <uv-button @click="cancel(item)"
                           type="error"
                           size="normal" plain
                           text="取消"></uv-button>
              </view>
            </view>

            <view class="accept" v-if="(item.identity==='2' && item.state === -1 && uid === item.memberId)">
              <view class="butt">
                <uv-button @click="toPay(item)" v-if="" type="danger"
                           :color="commonStyle.theme.color" size="normal" plain
                           text="去支付"></uv-button>
              </view>
            </view>


            <view class="accept" v-if="item.identity==='2' && item.state === 11 && uid === item.memberId">
              <view class="butt">
                <uv-button @click="audit(item,true)" v-if="item.state === 11" type="warning" :color="commonStyle.theme.color" size="normal"
                           plain
                           text="同意"></uv-button>
              </view>

              <view class="butt">
                <uv-button @click="audit(item,false)" v-if="item.state === 11" type="warning" :color="commonStyle.theme.color" size="normal"
                           plain
                           text="拒绝"></uv-button>
              </view>
            </view>
          </view>
        </slot>


        <view class="concat" v-if="(item.state === 11 || item.state === 2) ">
          <view class="phone-icon" @click="phoneCall(item.memberPhone||item.memberUser.phone)">
            <view class="text">
              用
            </view>
            <uv-icon size="25" color="#53c21d" name="/static/images/phone-icon1.png"></uv-icon>
            <view class="text">户</view>
          </view>
          <view v-if="(item.takerPhone||item.takerUser.phone)" class="phone-icon" @click="phoneCall(item.takerPhone||item.takerUser.phone)">
            <view class="text">
              跑
            </view>
            <uv-icon size="25" color="#53c21d" name="/static/images/phone-icon1.png"></uv-icon>
            <view class="text">
              手
            </view>
          </view>
        </view>
      </view>
      <uv-gap :height="10" v-if="!isLast" bgColor=""></uv-gap>
    </view>

    <uv-popup round="10" ref="signMadal" @change="change">
      <view style="padding: 20px">
        <view style="text-align: center;font-size: 17px;font-weight: bolder;margin-bottom: 10px">是否已经完成跑腿任务？</view>
        <view :style="{
          'text-align': 'left',
          'font-size': '14px',
          color: themConfig.theme.color
        }">
          <uv>
            <li>物品是否送达指定位置/交到用户手中</li>
            <li>是否通知用户物品送达指定地点</li>
          </uv>

        </view>
        <uv-form labelWidth="120" labelPosition="left" :model="form"  ref="form">
          <uv-form-item label="送达签收照片" prop="signForPictures" borderBottom>
            <UvUpload :upload_max="1" @uploadChange="uploadSuccess"/>
          </uv-form-item>
        </uv-form>
        <view style="margin-top: 10px">
          <uv-button @click="finish(null,true)" type="success" :color="commonStyle.theme.color" size="normal"
                     plain
                     text="确认完成"></uv-button>
        </view>
        <uv-gap height="45"/>
      </view>
    </uv-popup>

  </view>
</template>
<script>
import Dict from '@/components/school/dict';
import UvUpload from '@/components/school/uv-upload';
import SplitLine from '@/components/school/splitLine';
import * as LoginUtil from '@/libs/login.js';
import * as OrderApi from '@/api/school/order.js';
// import RichText from '@/components/school/richtext';
import {mapGetters} from "vuex";
import diyJson from '@/config/diy.js';

const app = getApp();
// 分割线
export default {
  computed: mapGetters(['uid', 'schoolId']),
  components: {
    Dict,
    UvUpload,
    SplitLine
    // ,RichText
  },
  data() {
    return {
      themConfig: diyJson.commonStyle,
      localDatas: this.datas,
      form:{
        signForPictures: '',
        id:''
      },
      finishItem:{}
    }
  },
  name: "OrderList",
  props: {
    commonStyle: {
      type: Object,
      default() {
        return {
          /* crmeb颜色变量 */
          theme: {
            color: "#cb6025",
          },
          font: {
            color: "#282828", // 常规字体颜色
            activeColor: "#E93323", // 字体激活颜色 和主题色一至
          },
        };
      }
    },
    isLast: {
      type: Boolean,
      default: function () {
        return true;
      }
    },
    custom: {
      type: Boolean,
      default: function () {
        return false
      }
    },
    datas: {
      type: [Array],
      default: function () {
        return []
      }
    },
    orderNo: {
      type: String,
      default: function () {
        return ''
      }
    },

    /**
     * 1=骑手
     * 2=发布人
     * 3=其他
     */
    type: {
      type: [String, Number],
      default: function () {
        return '1'
      }
    },
    properties: {
      type: Object,
      default: function () {
        return {
          "setStyle": {
            'borderRadius': 10,
            'backgroundColor': 'white',
            "pageMargin": 10,
            "padding": 10
          }
        }
      }
    },

  },
  watch: {
    orderNo: {
      handler(nVal, oVal) {
        if (nVal !== null && nVal !== '') {
          OrderApi.orderDetail(nVal).then(res => {
            this.localDatas = [res.data];
          })
        }
      },
      immediate: true, // 正确设置
      deep: true // 如果需要深度监听对象内部的变化
    }
    , datas: {
      handler(nVal, oVal) {
        if (nVal !== null && nVal.length > 0) {
          this.localDatas = nVal;
        }
      },
      immediate: true, // 正确设置
      deep: true // 如果需要深度监听对象内部的变化
    }
  },
  methods: {

    copyOrder(orderNo) {
      uni.setClipboardData({
        data: orderNo,
        success: function () {
          uni.showToast({
            title: '复制成功',
            icon: 'success',
            duration: 2000
          });
        }
      });
    },
    acctOrder(item) {
      if (!LoginUtil.checkLogin()) {
        LoginUtil.toLogin();
        return;
      }
      uni.showLoading({
        title: '处理中',
        mask: true
      });
      OrderApi.takeOrder({orderId: item.id}).then(res => {
        uni.hideLoading();
        this.$refs.notify.show({
          message: '已接单',
          duration: 500,
          safeAreaInsetTop: true
        });
        this.$emit("refresh", null);
        this.$emit("acctOrder", {orderId: item.id});
      })
    },
    cancel(item) {
      if (!LoginUtil.checkLogin()) {
        LoginUtil.toLogin();
        return;
      }

      uni.showLoading({
        title: '处理中',
        mask: true
      });

      OrderApi.cancelOrder({orderId: item.id}).then(res => {
        uni.hideLoading();
        this.$refs.notify.show({
          message: '已取消',
          duration: 500,
          safeAreaInsetTop: true
        });
        this.$emit("cancelOrder", {orderId: item.id});
        this.$emit("refresh", null);
      })
    },
    finish(item,confirm) {

      if (!LoginUtil.checkLogin()) {
        LoginUtil.toLogin();
        return;
      }

      if (!confirm){
        this.finishItem = item;
        this.$refs.signMadal.open('bottom');
        return;
      }


      OrderApi.doneOrder({orderId: this.finishItem.id,signForPictures:this.form.signForPictures}).then(res => {
        this.$refs.notify.show({
          message: '已完成',
          duration: 500,
          safeAreaInsetTop: true
        });
        this.$refs.signMadal.close();
        this.$emit("doneOrder", {orderId: this.finishItem.id});
        this.$emit("refresh", null);
      })
    },
    audit(item, state) {
      if (!LoginUtil.checkLogin()) {
        LoginUtil.toLogin();
        return;
      }
      OrderApi.auditOrder({orderId: item.id, state: state}).then(res => {
        this.$refs.notify.show({
          message: '已审核',
          duration: 500,
          safeAreaInsetTop: true
        });
        this.$emit("auditOrder", {orderId: item.id, state: state});
        this.$emit("refresh", null);
      })
    },
    phoneCall(phone) {
      console.log(phone)
      uni.makePhoneCall({
        phoneNumber: phone // 电话号码
      });
    },
    toPay(item) {
      let params = {
        outTradeNo: item.outTradeNo,
        amount: item.amount,
        body: item.orderName,
        payScene: 'ORDER'
      }
      this.$store.commit('SET_JUMP_INFO', params);
      uni.navigateTo({
        url: `/pages/school/pay/index?params=${encodeURIComponent(JSON.stringify(params))}`
      })
    },
    goDetail(item) {

      // let curentPath = window.location.href;
      // if (curentPath.indexOf('/pages/school/order-detail/index')>=0){
      //   return;
      // }
      //
      // this.$store.commit('SET_URL_PARAMS', {orderId: item.id});
      // uni.navigateTo({
      //   url: '/pages/school/order-detail/index?params=' + JSON.stringify({orderId: item.id})
      // });
      const targetPath = '/pages/school/order-detail/index';

      let isInDetailPage = false;
      // 判断当前页面是否已是详情页
      //#ifdef H5
        const curPath = window.location.href;
        isInDetailPage = curPath.indexOf(targetPath) >= 0;
      //#endif

      //#ifndef H5
        const pages = getCurrentPages();
        const currentPage = pages[pages.length - 1];
        isInDetailPage = currentPage.route === targetPath.replace(/^\//, '');
     // #endif

      if (isInDetailPage) return;

      // 保存参数到 Vuex
      this.$store.commit('SET_URL_PARAMS', { orderId: item.id });

      // 构造参数
      const queryParams = encodeURIComponent(JSON.stringify({ orderId: item.id }));

      // 执行跳转
      uni.navigateTo({
        url: `${targetPath}?params=${queryParams}`
      });
    },
    // <!-- 0=正常， 1=自主取消，2=超时未支付取消，4=管理员取消，3=超时无人接单取消,5=发布者审核拒绝 -->
    getCancelText(item) {
      if (item.cancelType === 1) {
        return '自主取消';
      } else if (item.cancelType === 2) {
        return '超时未支付取消';
      } else if (item.cancelType === 4) {
        return '平台取消';
      } else if (item.cancelType === 3) {
        return '超时无人接单取消';
      } else if (item.cancelType === 5) {
        return '拒绝接单取消';
      } else if (item.cancelType === 6) {
        return '拼团失败';
      } else {
        return ""
      }
    },

    uploadSuccess(array){
      console.log("array", array)
      if (array.images){
        this.form.signForPictures = array.images[0].url;
      }else {
        this.form.signForPictures = '';
      }
    }
  },
  created() {
    // console.log("properties orderList", this.properties)
    // console.log("properties orderList datas", this.datas)
    // console.log("properties orderNo", this.orderNo)
  }
  ,onShow(){
    this.$refs.signMadal.open('bottom');
  }
}
</script>

<style scoped lang="scss">
@import './index.scss';
</style>
